<?php
/**
* @package care_api
*/
/**
*/

require_once($root_path.'include/care_api_classes/class_core.php');
/**
*  Person methods. 
*
* Note this class should be instantiated only after a "$db" adodb  connector object  has been established by an adodb instance
* @author Jesus De Oliveira
* @version beta 2.0.1
* @package care_api
*/
class Usuario extends Core {
	/**#@+
	* @access private
	*/
	/**
	* Table name for interconsulta
	* @var string
	*/
        var $tb_usuario='care_users';
	/**
	* Table names for foreign keys
	* @var string
	*/

	/*** NONE ***/

	/**
	* SQL query
	*/
	var $sql;
	/**#@-*/
	/**
	* PID number
	* @var int
	*/
	var $login_id;
	/**
	* Sql query result buffer
	* @var adodb record object
	*/
	var $result;
	/**
	* Universal flag
	* @var boolean
	*/
	var $ok;
	/**
	* Internal data buffer
	* @var array
	*/
	var $data_array;
	/**
	* Internal data buffer 2
	* @var array
	*/
	var $data2_array;
	/**
	* Universal buffer
	* @var mixed
	*/
	var $buffer;
	/**
	* Returned row buffer
	* @var array
	*/
	var $row;
	/**
	* Returned usuario data buffer
	* @var array
	*/
	var $usuario=array();
	/**
	* Preloaded data flag
	* @var boolean
	*/
	var $is_preloaded=false;
	/**
	* Valid number flag
	* @var boolean,
	* @var array
	*/
	var $basic_list='name, matricula, clasificacion, login_id, password, permission, status';

	var  $elems_array=array(
				'name',
				'matricula',
				'clasificacion',
				 'login_id',
				 'password',
				 'permission',
				'status');


	/**
	* Constructor
	* @param int ID number
	*/
	function Usuario ($login_id='') {
	       $this->login_id=$login_id;
	       $this->ref_array=$this->elems_array;
	       $this->coretable=$this->tb_usuario;
	}
	/**
	* Sets the ID number.
	* @access public
	* @param int ID number
	*/
	function setID($login_id) {
	    $this->login_id=$login_id;
	}
	/**
	* Resolves the ID number to be used in the methods.
	* @access public
	* @param int ID number
	* @return boolean
	*/
	function internResolveID($login_id) {
	    if (empty($login_id)) {
		    if(empty($this->login_id)) {
			    return false;
			} else { return true; }
		} else {
		     $this->login_id=$login_id;
			return true;
		}
	}
	/**
	* Checks if ID number exists in the database.
	* @access public
	* @param int ID number
	* @return boolean
	*/
	/*function InitIDExists($init_nr){
		global $db;
		$this->sql="SELECT id FROM $this->tb_interconsulta WHERE id=$init_nr";
		if($this->result=$db->Execute($this->sql)){
			if($this->result->RecordCount()){
				return true;
			} else { return false; }
		} else { return false; }
		}*/
	/**
	* Prepares the internal buffer array for insertion routine.
	* @access private
	*/
	function prepInsertArray(){
	  global $_POST;
	  $x='';
	  $v='';
	  $this->data_array=NULL;
	  $this->data2_array=NULL;
	  
	  while(list($x,$v)=each($this->elems_array)) {
	    if(isset($_POST[$v])&&!empty($_POST[$v])) $this->data_array[$v]=$_POST[$v];
	  }
	  
	  
	}	
	/**
	* Database transaction. Uses the adodb transaction method.
	* @access private
	*/
	function Transact($sql='') {

	    global $db;
	    //$db->debug=true;
        if(!empty($sql)) $this->sql=$sql;

        $db->BeginTrans();
        $this->ok=$db->Execute($this->sql);
        if($this->ok) {
            $db->CommitTrans();
			return true;
        } else {
	        $db->RollbackTrans();
			return false;
	    }
    }	
	/**
	* Inserts the data into the care_users table.
	* @access private
	* @param int PID number
	* @return boolean
	*/
    function insertDataFromArray() {
		global $db;
		$array =$this->data_array;
		$array2 =$this->data2_array;
		$x='';
		$v='';
		$index='';
		$values='';

		if(is_array($array)){
			$x='';
			$v='';
			$index='';
			$values='';
			
			while(list($x,$v)=each($array)) {
				$index.="$x,";
				if (strcmp($x, "password") == 0) {
				  $values.="MD5('$v'),";
				} else {
				  $values.="'$v',";
				}
			} 
			$index=substr_replace($index,'',(strlen($index))-1);
			$values=substr_replace($values,'',(strlen($values))-1);
	
			$this->sql="INSERT INTO $this->tb_usuario ($index) VALUES ($values)";
	
// 			echo $this->sql;
			$b = $this->Transact();

		}else{
			return false;
		}
		return $b;
	}

	/**
	* Inserts the data from the internal buffer array into the care_person table.
	*
	* The data must be packed in the buffer array with index keys as outlined in the <var>$elems_array</var> array.
	* @access public
	* @return boolean
	*/
	function insertDataFromInternalArray() {
            global $_POST;
	    //$this->data_array=NULL;
		$this->prepInsertArray();
		$b = $this->insertDataFromArray();
		return $b;
	}


	function updateDataFromInternalArray($login_id) {
		global $_POST;

                $this->login_id = $login_id;
		$this->prepInsertArray();
		return $this->updateDataFromArray($this->data_array,$login_id);
	}


    function updateDataFromArray(&$array,$login_id='') {
		$x='';
		$v='';
		$sql='';
		
		if(!is_array($array)) return false;
		if(empty($login_id)) return false;
		while(list($x,$v)=each($array)) {
		  if(stristr($v,'concat')||stristr($v,'null')) {
		    $sql.="$x= $v,";
		  } else {
		    if ((strcmp($x, "password") == 0) && !empty($v)) {
		      $sql=" $x=MD5('$v'),";
		    } else {
		      $sql.="$x='$v',";
		    }
		  }
		}
		$sql=substr_replace($sql,'',(strlen($sql))-1);
		
        $this->sql="UPDATE $this->tb_usuario SET $sql WHERE login_id='$login_id'";
// 		echo $this->sql;
		return $this->Transact();
	}

	/**
	* Gets all usuario information based on its ID number key.
	*
	* The returned adodb record object contains a row or array.
	* This array contains data with the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - addr_citytown_name = name of the city or town
	*
	* @access public
	* @param int ID number
	* @return mixed adodb object or boolean
	*/
	function getAllInfoObject($login_id) {
	  global $db;
	  
	  $this->sql="SELECT 
		i.*
		FROM $this->tb_usuario AS i
		WHERE i.login_id='$login_id'";
	  
	  //echo $this->sql;
	  if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
	      return $this->result;	 
	    } else { 
	      return false; }
	  } else { 
	    return false; 
	  }
	}
	/**
	* Same as getAllInfoObject() but returns a 2 dimensional array.
	*
	* The returned  data in the array have the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - citytown = name of the city or town
	*
	* @access public
	* @param int PID number
	* @return mixed array or boolean
	*/
	/*function getAllInfoArray($id='') {
	    global $db;
		 $x='';
		 $v='';
		if(!$this->internResolveID($id)) return false;
		
	    $this->sql="SELECT i.*, esp.descripcion AS especialidad_descripcion, esp.id id_especialidad
					FROM $this->tb_interconsulta AS i
					LEFT JOIN  $this->tb_especialidad AS esp ON i.id_especialidad = esp.id
					WHERE i.id='$this->id' ";

        	if($this->result=$db->Execute($this->sql)) {

			if($this->result->RecordCount()) {
				return $this->row=$this->result->FetchRow();
			} else { return false; }
		} else { return false; }
		}*/

	/**
	* Gets a particular usuario based on its LOGIN ID .
	*
	* Use this preferably after the person registration data was successfully preloaded in the internal buffer with the <var>preloadPersonInfo()</var> method.
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* @access private
	* @param string Field name of the item to be fetched
	* @param int ID number
	* @return mixed string, integer, or boolean
	*/
	function getValue($item,$login_id='') {
	    global $db;

	    if($this->is_preloaded) {
		    if(isset($this->usuario[$item])) return $this->usuario[$item];
		        else  return false;
		} else {
		    if(!$this->internResolveID($login_id)) return false;
		    $this->sql="SELECT $item FROM $this->tb_usuario WHERE login_id=$this->login_id";
		    //return $this->sql;
           		 if($this->result=$db->Execute($this->sql)) {
                		if($this->result->RecordCount()) {
				     $this->usuario=$this->result->FetchRow();
				     return $this->usuario[$item];
			    } else { return false; }
		    } else { return false; }
		}
	}
	/**
	* Gets interconsultas based on an item list and ID number.
	*
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* Several items can be fetched at once but their field names must be separated by comma.
	* @access public
	* @param string Field names of items to be fetched separated by comma.
	* @param int ID number
	* @return mixed
	*/
	function getValueByList($list,$login_id='') {
	    global $db;
	
		if(empty($list)) return false;
		if(!$this->internResolveID($login_id)) return false;
		$this->sql="SELECT $list FROM $this->tb_usuario WHERE login_id=$login_id";
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				$this->usuarios=$this->result->FetchRow();	 
				return $this->usuarios;
			} else { return false; }
		} else { return false; }
	}

	function getValueBy($login_id = '', $name = '') {
	    global $db;


                $where = '';

                if (!empty($login_id))
                {
                    $where = " login_id LIKE '%$login_id%'";
                }

                if (!empty($name))
                {
		  if ($where) {
                    $where .= " AND name LIKE '%$name%'";
		  } else {
                    $where = " name LIKE '%$name%'";
		  }
                }

		$result=array();
		$q="SELECT * FROM care_users ";

		if ($where){
			$q.= " WHERE ".$where;
		}

//                 echo $q;

		$this->sql=$q;
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}
	}


	
	function DatosPaciente() {
        return  $this->getValue('id_datos_paciente');
	}

	/**
	* Returns interconsulta items as listed in the <var>$basic_list</var> array based on pid key.
	*
	* The data is returned as associative array.
	* @access public
	* @param int PID number
	* @return mixed string or boolean
	*/
	function BasicDataArray($login_id){
        if(!$this->internResolveID($login_id)) return false;
		return $this->getValueByList($this->basic_list,$this->login_id);
	}

	/**
	* Searches and returns a list of interconsultas based on search key.
	*
	* The returned adodb record object contains rows of arrays.
	* Each array contains the encounter data with the following index keys:
	* - especialidad
	* - establecimiento
	* - status (id_interconsultado null)
	* - interconsultante
        * - interconsultado
	* - fecha_hora_consulta
        * - fecha_hora_respuesta
	*
	* @access public
	* @param string Search keyword
	* @param string Sort by the item name, default = name_last (last/family name)
	*�@param string Sort direction, default = ASC (ascending)
	* @return mixed integer or boolean
	*/
	function Interconsultas($searchkey='',$order_item='login_id',$order_dir='ASC'){
	    global $db, $sql_LIKE;
		$searchkey=trim($searchkey);
		$searchkey=strtr($searchkey,'*?','%_');
		
		if(empty($order_item)) $order_item='login_id';
		if(empty($order_dir)) $order_dir='ASC';
		$this->is_nr=false;
		
		
		return $this->SearchSelect($searchkey,'','',$order_item,$order_dir);
        }



}
?>
